package ext.rest;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;;

@SuppressWarnings("deprecation")
public class testRestAPI {
	/**
	 * 直接在Java Main方法中执行即可
	 */
	
	
	/**
	 * 无参数
	 */
	public void testRestGetMethod() {
		try {
			String baseUrl = "/Windchill/servlet/rest";
			String servicePath = baseUrl + "/v1/wcobj/users";
			String host = "plm-training.elead.cn";
			URI uri = URIUtils.createURI("http", host, 80, servicePath, null, null);
			System.out.println("uri:" + uri.toString());
			// 身份认证代码，企业级环境中，应该通过配置文件管理，配置文件中使用加密字符串，此处代码需要读取配置文件中的用户名和密码，进行解密，不应该使用明文
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			// credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new
			// UsernamePasswordCredentials("orgadmin", "orgadmin"));
			credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
					new UsernamePasswordCredentials("wcadmin", "wcadmin"));
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

			HttpGet httpget = new HttpGet(uri);
			CloseableHttpResponse response = httpclient.execute(httpget);

			try {
				// 获取服务响应状态，如果状态值为200，则表示服务调用成功
				System.out.println("Response Status: " + response.getStatusLine());
				HttpEntity entity = response.getEntity();
				// 输出返回信息
				if (entity != null) {
					String resStr = EntityUtils.toString(entity, "UTF-8");
					System.out.println("result:" + resStr);
					JSONObject map = new JSONObject(resStr);
					JsonFile("C:\\Users\\Administrator\\Desktop", "", map.toString());
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public void testRestGetMethod(String number) {
		try {
			String baseUrl = "/Windchill/servlet/rest";
//			String servicePath = baseUrl + "/v1/wcobj/getPartByNumber/{number}";
			String servicePath = baseUrl + "/v1/wcobj/getPartByNumber";
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("number", number));

			// URLEncodedUtils用于处理中文参数
			String param = URLEncodedUtils.format(params, "UTF-8");
			System.out.println(param);
			
			String host = "plm-training.elead.cn";
			URI uri = URIUtils.createURI("http", host, 80, servicePath, number, null);
			System.out.println(uri.toString());
			// 身份认证代码，企业级环境中，应该通过配置文件管理，配置文件中使用加密字符串，此处代码需要读取配置文件中的用户名和密码，进行解密，不应该使用明文
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			// credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new
			// UsernamePasswordCredentials("orgadmin", "orgadmin"));
			credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
					new UsernamePasswordCredentials("wcadmin", "wcadmin"));
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

			HttpGet httpget = new HttpGet(uri);
			CloseableHttpResponse response = httpclient.execute(httpget);

			try {
				// 获取服务响应状态，如果状态值为200，则表示服务调用成功
				System.out.println("Response Status: " + response.getStatusLine());
				HttpEntity entity = response.getEntity();
				// 输出返回信息
				if (entity != null) {
					String resStr = EntityUtils.toString(entity, "UTF-8");
					System.out.println(resStr);
					JSONObject map = new JSONObject(resStr);
					JsonFile("C:\\Users\\Administrator\\Desktop", "", map.toString());
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void testRestGetMethod(List<NameValuePair> paramss) {
		try {

			// 添加参数列表
			List<NameValuePair> params = new ArrayList<NameValuePair>();

			String baseUrl = "/Windchill/servlet/rest";

			String servicePath = baseUrl + "/v1/sany/service/sysc-WorkCenter";
			params.add(
					new BasicNameValuePair("workCenterBeans", "{'werks':'werks1','arbpl':'arbpl1','stext':'stext1'}"));
			params.add(
					new BasicNameValuePair("workCenterBeans", "{'werks':'werks2','arbpl':'arbpl2','stext':'stext2'}"));
			params.add(
					new BasicNameValuePair("workCenterBeans", "{'werks':'werks3','arbpl':'arbpl3','stext':'stext3'}"));
			params.add(
					new BasicNameValuePair("workCenterBeans", "{'werks':'werks4','arbpl':'arbpl4','stext':'stext4'}"));

			// URLEncodedUtils用于处理中文参数
			String param = URLEncodedUtils.format(params, "UTF-8");
			System.out.println(param);
			String host = "plm-training.elead.cn";
			URI uri = URIUtils.createURI("http", host, 80, servicePath, param, null);
			System.out.println(uri.toString());
			// 身份认证代码，企业级环境中，应该通过配置文件管理，配置文件中使用加密字符串，此处代码需要读取配置文件中的用户名和密码，进行解密，不应该使用明文
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			// credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new
			// UsernamePasswordCredentials("orgadmin", "orgadmin"));
			credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
					new UsernamePasswordCredentials("wcadmin", "wcadmin"));
			CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

			HttpGet httpget = new HttpGet(uri);
			CloseableHttpResponse response = httpclient.execute(httpget);

			try {
				// 获取服务响应状态，如果状态值为200，则表示服务调用成功
				System.out.println("Response Status: " + response.getStatusLine());
				HttpEntity entity = response.getEntity();
				// 输出返回信息
				if (entity != null) {
					String resStr = EntityUtils.toString(entity, "UTF-8");
					System.out.println(resStr);
					JSONObject map = new JSONObject(resStr);
					JsonFile("C:\\Users\\Administrator\\Desktop", "", map.toString());
				}
			} finally {
				response.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void JsonFile(String path, String FileName, String Message) {
		System.out.println("**message：" + Message);
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
		FileName = dateFormat.format(now).toString() + ".json";
		FileWriter fw = null;
		File f = new File(path + "/" + FileName);

		try {
			File destPar = new File(path);

			if (!destPar.exists()) {
				destPar.mkdirs();
			}

			if (!f.exists()) {
				f.createNewFile();
			}
			fw = new FileWriter(f);
			BufferedWriter out = new BufferedWriter(fw);
			out.write(Message);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(FileName + "end,next...");
		System.out.println(" ");
	}

	public static void main(String[] args) throws Exception {

		testRestAPI client = new testRestAPI();
		client.testRestGetMethod();
//		client.testRestGetMethod("0000000261");
	}

}
